package com.qubuyer.base.listener;

import android.widget.OverScroller;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.lang.reflect.Field;

public class OptimizeLoadUtil {
    public static void optimizeImgLoad(RecyclerView recyclerView) {
        Class java = RecyclerView.class;
        Field viewFlinger = null;
        try {
            viewFlinger = java.getDeclaredField("mViewFlinger");
            viewFlinger.setAccessible(true);
            Object vf = viewFlinger.get(recyclerView);
            Class[] declaringClass = java.getDeclaredClasses();
            Class clazz = null;
            for (Class dc : declaringClass) {
                if (dc.getName().contains("ViewFlinger")) {
                    clazz = dc;
                }
            }
            Field field = clazz.getDeclaredField("mOverScroller");
            field.setAccessible(true);
            OverScroller scroller = (OverScroller) field.get(vf);
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                boolean hasPause = false;
                int state = RecyclerView.SCROLL_STATE_IDLE;

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    if (state == RecyclerView.SCROLL_STATE_SETTLING) {
                        float speed = scroller.getCurrVelocity();
                        if (hasPause && speed < 1000) {
                            //惯性滑动以每秒小于1000像素的滑动距离作为慢速滑动，慢速滑动时恢复Glide图片加载
                            hasPause = false;
                            Glide.with(recyclerView.getContext()).resumeRequests();
                        }
                        if (speed >= 1000) {
                            //惯性滑动以每秒大于1000像素的滑动距离作为快速滑动，快速滑动时z暂停Glide图片加载
                            hasPause = true;
                            Glide.with(recyclerView.getContext()).pauseRequests();
                        }
                    }
                }

                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    state = newState;
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        if (hasPause) {
                            //滚动停止时判断是否暂停过图片加载，如果有则恢复加载
                            hasPause = false;
                            Glide.with(recyclerView.getContext()).resumeRequests();
                        }
                    }
                }
            });
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
